// StepsPage.jsx  
import React, { useState,useEffect } from 'react';  
import { Steps, Button,Spin, Card } from 'antd';  
import BasicInfoForm from '../step/step1';  
import FileUpload from '../step/step2';  
import Step3 from '../step/step3';  
import Step4 from '../step/step4';
import Step5 from '../step/step5';
import Step6 from '../step/step6';      
import {useTranslation} from 'react-i18next'
import { listCv} from "@/api/modules/cv";
import { template,add,editProduct,addFm,editFm,subjectTestResult,updateSubjectTestResult,createReport,separatedFm,separatedFix,separatedCreateReport,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";
import FullscreenLoading from '@/components/FullscreenLoading';
import { FormOutlined ,ArrowUpOutlined,TableOutlined,FileTextOutlined,CloudUploadOutlined,CloudDownloadOutlined} from '@ant-design/icons'; 
import useCacheAlive from '@/hooks/useCacheAlive';

const { Step } = Steps;  
  
const addreport = () => {  
  const { t } = useTranslation();
  const [CVList,setCVList]  = useState([]);
  const [current, setCurrent] =  useCacheAlive(0, `table-addreport-current`) 
  const [step1Value, setStep1] = useCacheAlive({}, `table-addreport-step1Value`) 
  const [step2formValues, setFormValues] =  useCacheAlive({}, `table-addreport-step2formValues`) 
  const [step2Table, setStep2Table] =useCacheAlive([], `table-addreport-step2Table`)
  const [step3formValues, setStep3FormValues] = useCacheAlive({}, `table-addreport-step3formValues`)
  const [step4formValues, setStep4FormValues] =  useCacheAlive({}, `table-addreport-step4formValues`)
  const [step5formValues, setStep5FormValues] = useCacheAlive({}, `table-addreport-step5formValues`)
  const [safety_product_id, setSafety_product_id] = useCacheAlive({}, `table-addreport-safety_product_id`)
  const [report_id, setReport_id] = useCacheAlive(0, `table-addreport-report_id`)
  const [loading, setLoading] = useState(false); 

  useEffect(() => { 
    listCv().then(res=>{
      setCVList(res.data.rows)
      })
     let productId  =  getQueryVariable("productId")
      if (productId) {  
        // 使用productId进行某些操作，比如发起请求获取产品数据  
        setSafety_product_id(productId)
        // fetchProductData(productId);  
      } else {  
        setSafety_product_id(0)
      }  
    }, []); // 当productId变化时，这个effect会重新运行  

 const getQueryVariable = (variable) =>{
  const query = window.location.search.substring(1);
  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split("=");
      if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}

  const handleNext = (phase,rawData) => {  
    console.log(phase,'phase')
    console.log(rawData,'rawData')
    if(phase == '1'){
      if(rawData !== ''){
        setStep2Table(rawData)
      }
      setCurrent(1);  
    }else if(phase == '2'){
      setStep3FormValues(rawData)
      setReport_id(rawData.id)
      setCurrent(2);   
    }else if(phase == '3'){
      setStep4FormValues(rawData)
      setCurrent(3);  
    }else if(phase == '4'){
      setStep5FormValues(rawData)
      setCurrent(4);
    }else if(phase == '5'){
      setCurrent(5); 
    }
  };  
  

  
  const handleFinish = (values) => {  
      // 当表单提交时，设置表单值并推进到下一步  
      setLoading(true);  // 开始加载时设置为 true  
      setFormValues(values);  
      values.efficacy = values.efficacy .join("，");
      values.form = values.form .join("，");
      values.method = values.method.join("，");
      values.population = values.population.join("，");
      values.people = values.people.join("，");
      values.position = values.position.join("，");
      //暴露量特殊处理，使用英文逗号
      values.classification = values.classification.join(",");
      values.productStatus='NoApproval'
      CVList.map(i=>{
          if(i.id==values.safetyCvId){
            values.appraiser=i.name
          }
      })
      console.log(safety_product_id,'PRODUCTID')
      if(safety_product_id==0){
        add(values).then(res=>{
          console.log(res,'res')
          if(res.code==200){
            if (values.id == null || values.id == undefined || values.id == "") {
              setSafety_product_id(res.data.data)
              values.id=res.data.data
            } else {
              setSafety_product_id(values.id)
            }
            values.fm_number= values.productCode
            setFormValues(values)
            setStep1(values);
            handleNext('1','')
            setLoading(false); 
          }
          
        })
      }else{
        values.id = safety_product_id
        editProduct(values).then(res=>{
          console.log(res,'res')
          if(res.code==200){
            if (values.id == null || values.id == undefined || values.id == "") {
              setSafety_product_id(res.data.data[0].safetyProductId)
            } else {
              setSafety_product_id(values.id)
            }
            values.fm_number= values.productCode
            setFormValues(values)
            handleNext('1',res.data.data[0])
            setLoading(false); 
          }
          
        })
      }

     
  };  
  
  const renderContent = (current) => {  
    switch (current) {  
      case 0:  
        return <BasicInfoForm onFinish={handleFinish} productId={safety_product_id} step1Value={step1Value}/>;  
      case 1:  
        return <FileUpload formData={step2formValues} tableData={step2Table} onUploadSuccess={handleNext} />;  
      case 2:
        return <Step3 formData={step3formValues} onUploadSuccess={handleNext} ></Step3>
      case 3:
        return <Step4 formData={step4formValues} onUploadSuccess={handleNext} ></Step4>
      case 4:
          return <Step5 formData={step5formValues} productId={safety_product_id} onUploadSuccess={handleNext} ></Step5> 
      case 5:
          return <Step6 formData={report_id} onUploadSuccess={handleNext} ></Step6> 
      default:  
        return '完成';  
    }  
  };  

  const handleStepClick = (index) => {  
    // 只允许点击小于或等于当前步骤的步骤  
    if (index < current) { 
      if(index==0){
        setCurrent(index); 
      }else if(index==1){
        setLoading(true);  // 开始加载时设置为 true 
        console.log(step2formValues,'data')
        let rawData = step2formValues
        editProduct(rawData).then(res=>{
          if(res.code==200){
            setFormValues(rawData)
            if(res.data.data[0] !== ''){
              setStep2Table(res.data.data[0])
            }
            setCurrent(1); 
            setLoading(false); 
          }
        })
      }else if (index==2){
        setCurrent(index); 
      }else if (index==3){
        setCurrent(index); 
      }else if (index==4){
        setCurrent(index); 
      }    
 
      // 在这里可以添加跳转到对应步骤内容的逻辑，比如更新状态、导航等  
    }  
  };  
  
  return (  
    <div>  
      <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
      <Card>
        <Steps current={current} >  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(0)} title={t('inputReportDetail')} icon={<FormOutlined />}/>  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(1)} title={t('formulaUpload')} icon={<ArrowUpOutlined/>}/>  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(2)} title={t('formulaCompositionConfirmation')} icon={<TableOutlined />}/>  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(3)} title={t('VerificationandModification')} icon={<FileTextOutlined/>}/> 
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(4)} title={t('CommentReference')} icon={<CloudUploadOutlined/>}/>  
          <Step style={{cursor: 'pointer'}} onClick={() => handleStepClick(5)} title={t('addReport')} icon={<CloudDownloadOutlined/>}/> 
        </Steps> 
      </Card>
       
      <div style={{ marginTop: 16 }}>{renderContent(current)}</div>  
     
    </div>  
  );  
};  
  
export default addreport;